package ranab;

import java.io.File;
import java.io.OutputStream;
import java.util.Map;
import java.util.Hashtable;

import javax.servlet.*;
import javax.servlet.http.*;

import ranab.tpl.Template;
import ranab.io.IoUtils;

/**
 * This is the base servlet of all the servlets. It encapsulates
 * template loading, error handling.
 *
 * @author <a href="mailto:rana_b@yahoo.com">Rana Bhattacharyya</a>
 */

public
class BaseServlet extends HttpServlet {

    // Here the document root is hard coded.
    // It is not a very good idea. The better approach
    // is to use servlet init params or get it from the 
    // servlet context.
    private static File DOC_ROOT = new File("/home/ranab/template");


    private static Template PROBLEM_TPL = null;
    private static Template ERROR_TPL = null;


    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        File docRoot = getDocRoot();
        PROBLEM_TPL = new Template(new File(docRoot, "template/problem.txt"));
        ERROR_TPL = new Template(new File(docRoot, "template/error.txt"));
    }

    // dummay methods
    protected File getDocRoot()  {
        return DOC_ROOT;
    }

    protected File getDocRoot(ServletConfig cfg)  {
        return getDocRoot();
    }

    protected File getDocRoot(ServletContext ctx)  {
        return getDocRoot();
    }


    // load template file with error correction
    protected void loadFile(Template tpl, OutputStream out, Map hash)  {
        try {
            tpl.loadFile(out, hash);
        } catch (Exception ex) {
            showProblemPage(out, ex);
        }
    }

    // show error page
    protected void showErrorPage(OutputStream out, String msg)  {
        try {
            Hashtable hash = new Hashtable();
            hash.put("message", msg);
            ERROR_TPL.loadFile(out, hash);
        } catch (Exception ex) {
        }
    } 

    // display problem page
    protected void showProblemPage(OutputStream out, String msg)  {
        try {
            Hashtable hash = new Hashtable();
            hash.put("message", msg);
            PROBLEM_TPL.loadFile(out, hash);
        } catch (Exception ex) {
        }
    }

    // display problem page with exception stack trace
    protected void showProblemPage(OutputStream out, Exception ex)  {
        try {
            Hashtable hash = new Hashtable();
            hash.put("message", IoUtils.getStackTrace(ex));
            PROBLEM_TPL.loadFile(out, hash);
        } catch (Exception e) {
        }
    }
}
